from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response, CacheResponse
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView
from areas.serializers import AreasSerialzier, AddressSerialzier
from users.models import Address


# Create your views here.
# 获取省的信息


class AreasView(CacheResponseMixin, ListAPIView):
    serializer_class = AreasSerialzier
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin, ListAPIView):
    serializer_class = AreasSerialzier

    # queryset = Area.objects.filter(parent_id=pk)
    # 装饰器形式
    # @cache_response(timeout=60*60,cache='default')
    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


# 新增收货地址
class AddressView(CreateAPIView, UpdateAPIView, ListAPIView):
    serializer_class = AddressSerialzier

    # queryset = Address.objects.filter()
    def get_queryset(self):
        return Address.objects.filter(user=self.request.user, is_deleted=False)

    def delete(self, request, pk):
        obj = self.get_object()
        obj.is_deleted = True
        obj.save()
        return Response()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'addresses': serializer.data, 'default_address_id': self.request.user.default_address_id})
